<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>粉丝聊天室</title>
    <script src="js/jquery.min.js"></script>
    <link rel="stylesheet" href="css/index.css">
</head>

<body>
    <div>
        <h1>欢迎来到大型交友网站~</h1>
    </div>
    <div class="container-left">
        <span>聊天框</span>
        <div class="chat-area">
            <!-- 聊天内容 -->
        </div>
        <hr>
        <div class="online-advice">
            <span>上下线通知</span>
        </div>
    </div>
    <div>
        <textarea name="send-msg" id="send-msg" cols="30" rows="10"></textarea>
        <button type="submit" onclick="sendMsg()">发送(send)</button>
    </div>

    <script>

        var curUsername = "";
        var curUserId = -1;

        var host = window.location.host;
        var webSocket = new WebSocket("ws://" + host + "/chat");
        webSocket.onopen = function () {
            console.log("连接成功!");
        }
        webSocket.onclose = function () {
            console.log("连接断开!");
        }
        webSocket.onerror = function () {
            console.log("连接异常!");
        }
        window.onbeforeunload = function () {
            webSocket.close();
        }
        //接收消息
        webSocket.onmessage = function (e) {
            //获取服务器传来的数据
            var jsoninfo = e.data;
            //将 json 信息转化为 js 对象
            var result = JSON.parse(jsoninfo);

            //获取上下线通知
            var onlineAdvice = jQuery(".online-advice");
            if(result != null) {
                if(result.msg == "many") {
                    //同一个账号多次登录
                    alert("当前用户已登录，不可再次登录!");
                    location.href = "/login.html";
                } else if(result.msg == "online") {
                    var advice = '<div class="open">'+result.data.username+'上线</div>';
                    onlineAdvice.append(advice);
                } else if(result.msg == "exception") {
                    //用户登录异常
                    alert("当前用户登录异常, 请重新登录!");
                    location.href = "/login.html";
                } else if(result.msg == "out") {
                    //用户断开连接
                    var advice = '<div class="out">'+result.data.username+'下线</div>';
                    onlineAdvice.append(advice);
                    jQuery("#user"+result.code+"").remove();
                } else {
                    //接收到其他用户推送的消息
                    var chatMsg = "";
                    chatMsg += '<div class="chat-msg">';
                    chatMsg += '<span class="target">'+result.data.username+'：</span>';
                    chatMsg += '<span class="msg">'+result.msg+'</span>';
                    chatMsg += '</div>';
                    jQuery(".chat-area").append(chatMsg);
                }
            } else {
                alert("信息传输异常!");
            }


        }


        //获取当前登录用户的信息
        function curUser() {
            jQuery.ajax({
                type: "GET",
                url: "/user/cur-user",
                data: {},
                success: function(result) {
                    if(result != null && result.code == 200) {
                        curUsername = result.data.username;
                        curUserId = result.data.id;
                    } else {
                        alert("当前用户信息获取失败!");
                    }
                }
            });
        }
        curUser();

        //发送消息
        function sendMsg() {
            var msg = jQuery("#send-msg").val();
            if(msg == null || msg == "") {
                alert("发送内容不能为空!");
                return;
            }

            // //请求缓存
            // jQuery.ajax({
            //     type: "POST",
            //     url: "/user/msg_cache",
            //     data: {
            //         "username": curUsername,
            //         "msg": msg
            //     },
            //     success: function(result) {
            //         if(result != null && result.code == 200) {
            //             console.log("消息缓存成功!");
            //         } else {
            //             console.log("消息缓存失败!");
            //         }
            //     }
            // });

            //先检测连接是否正常
            if(webSocket.readyState == webSocket.OPEN) {
                //客户端展示
                var chatDiv = ""; 
                chatDiv += '<div class="chat-msg">';
                chatDiv += '<span class="me">'+curUsername+'：</span>';
                chatDiv += '<span class="msg">'+msg+'</span>';
                chatDiv += ' </div>';
                jQuery(".chat-area").append(chatDiv);
                //将消息发送给服务器
                var json = {
                    "code": curUserId,
                    "msg": msg
                };
                webSocket.send(JSON.stringify(json));
            } else {
                alert("当前连接异常，请重新登录!");
                location.href = "/login.html";
            }

        }


    </script>

</body>

</html>